<template>
  <div class="personalAuth_page">
    <van-nav-bar title="企业招聘信息填写" left-arrow @click-left="$router.push('/mine')" />

    <van-form @submit="handleSubmit">
      <van-field
        autocomplete="off"
        v-model="telephone"
        name="Telephone"
        label="招聘职位"
        placeholder="请输入招聘职位"
        :rules="[{required: true, message: '未填写'}]"
        :disabled="disabled"
        required
      />
      <!-- <van-field autocomplete="off" name="idCardFrontPhoto" label="上传毕业证"
                 :rules="[{ required: true, message: '上传毕业证' }]"
                 :disabled="disabled"
                 required
      >
        <template #input>
          <van-uploader
            :delete="idCardFrontPhoto = ''"
            :deletable="deletable"
            :preview-options="{
              closeable: true,
            }"
            v-model="id_card_front_photo" :max-count="1" :after-read="afterRead1"
          />
        </template>
      </van-field> -->
      <van-field
        autocomplete="off"
        v-model="email"
        name="Email"
        label="薪资福利"
        placeholder="请输入薪资福利"
        :disabled="disabled"
      />

      <van-field
        autocomplete="off"
        v-model="qqNum"
        name="qqNum"
        label="招聘要求"
        placeholder="请输入招聘要求"
        :disabled="disabled"
      />

      <van-field
        autocomplete="off"
        v-model="qqNum"
        name="qqNum"
        label="联系电话"
        placeholder="请输入联系电话"
        :disabled="disabled"
      />

      <!-- 提交   -->
      <div style="margin: 16px;">
        <van-button round block :type="isUpdate ? 'danger' : 'info'">
          {{ isUpdate ? '确定修改' : '上传招聘信息' }}</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import {Toast} from 'vant'
import {mapGetters} from 'vuex'
import auditState from '../../constants/auditState'
import {idCardReg} from '../../constants/comUtils'
import {cosUploadImg} from '@/utils/cosUpload.js'

const genderIdList = [
  {
    key: '0',
    value: '女'
  },
  {
    key: '1',
    value: '男'
  }
]

export default {
  name: 'resumeDetail',
  data() {
    return {
      idPattern: idCardReg,
      // 设计的状态
      auditState,
      // 图片预览时是否可删除,
      // 默认是可删除, 但是一旦提交认证过就不可删除
      disabled: false,
      deletable: true,
      currentState: '未认证， 请先认证！',
      isUpdate: false,

      // 表单中的值
      name: '',
      idCard: '',
      telephone: '',
      email: '',
      qqNum: '',
      wxNum: '',
      gender_id: '',
      genderIdList,
      id_card_front_photo: [],
      // 后端需要
      idCardFrontPhoto: '',
      id_card_back_photo: [],
      // 后端需要
      idCardBackPhoto: '',
      personPictures: [],
      // 后端需要
      picturesString: '',
      start_date: '',
      end_date: '',
      showStartPicker: false,
      showEndPicker: false,
      minDate: new Date(1950, 0, 1),
      maxDate: new Date(2100, 10, 1),
      currentDate: new Date()
    }
  },
  created() {
    // 避免刷新时，出现的bug
    // 只有这两种情况讨论： 0、未认证;  1、认证中;  2、认证成功; 3 驳回（认证失败）
    if (this.allUserInfo.certification_state != 0) {
      // 只有提交过认证后, 才请求个人认证详细信息
      this.$store.dispatch('getUserAuditInfo')
    }
  },
  watch: {
    // 监视
    // 谨慎使用监视, 坑太多
    userAuditInfo: {
      deep: true,
      handler(newValue, oldVal) {
        if (JSON.stringify(newValue) != '{}') {
          // 更新状态
          if (newValue.audit_state != 3) {
            this.disabled = true
            this.deletable = false
            this.isUpdate = false
          } else {
            // 验证审核失败时
            this.disabled = false
            this.deletable = true
            this.isUpdate = true
          }
          // form表单中的值
          this.name = newValue.name
          this.idCard = newValue.card_id
          this.telephone = newValue.line_mobile
          this.email = newValue.email
          this.qqNum = newValue.qq_num
          this.wxNum = newValue.wx_num
          this.gender_id = newValue.gender ? '1' : '0'

          // 这是由于van-uploader组件渲染时， 执行了delete方法。因此使用this.$nextTick。dom渲染完后，再执行和更新状态。
          this.$nextTick(() => {
            // 需要的图片链接地址
            this.idCardFrontPhoto = newValue.positive_id
            this.idCardBackPhoto = newValue.negative_id
            this.picturesString = newValue.hand_id_card
          })

          this.id_card_front_photo.push({url: newValue.positive_id})
          this.id_card_back_photo.push({url: newValue.negative_id})
          this.personPictures.push({url: newValue.hand_id_card})
          this.start_date = this.$needDateFormat(newValue.validity_start_time, 'yyyy-MM-dd')
          this.end_date = this.$needDateFormat(newValue.validity_end_eime, 'yyyy-MM-dd')
        }
      }
    }
  },
  computed: {
    ...mapGetters(['userAuditInfo', 'allUserInfo']),

    computedAuditState() {
      let result
      if (this.userAuditInfo.audit_state_desc) {
        result = this.userAuditInfo.audit_state_desc
      } else {
        result = this.currentState
      }
      return result
    }
  },
  methods: {
    // 封装函数
    async _reqUploadPicture(picture) {
      let formData = new FormData()
      formData.append('filename', picture.file)
      const img_type = 'user_certification'
      // const res = await this.$api.uploadImg.uploadPhotos(formData, img_type)
      const res = await cosUploadImg(picture.file, img_type)
      if (res.code === 200) {
        return res.data
      }
    },

    afterRead1(picture) {
      // async/await函数的返回结果仍是promise对象, 使用.then()取得返回值
      this._reqUploadPicture(picture).then(res => {
        this.idCardFrontPhoto = res
      })
    },
    afterRead2(picture) {
      this._reqUploadPicture(picture).then(res => {
        this.idCardBackPhoto = res
      })
    },
    afterRead3(picture) {
      this._reqUploadPicture(picture).then(res => {
        this.picturesString = res
      })
    },
    handleShowStartPicker() {
      this.showStartPicker = !this.disabled
    },

    handleShowEndPicker() {
      this.showEndPicker = !this.disabled
    },

    confirmStartDate(time) {
      this.start_date = this.$needDateFormat(time, 'yyyy-MM-dd')
      this.showStartPicker = false
    },
    confirmEndDate(time) {
      this.end_date = this.$needDateFormat(time, 'yyyy-MM-dd')
      this.showEndPicker = false
    },

    async handleSubmit(values) {
      if (this.start_date.replace(/-/g, '') * 1 >= this.end_date.replace(/-/g, '') * 1) {
        Toast('法人身份证起止日期不合法，请修改！')
      } else {
        const {Name, IdCard, Telephone, Email, QQNum, WxNum, genderId, startingDate, endDate} = values
        const params = {
          name: Name,
          card_id: IdCard,
          line_mobile: Telephone,
          positive_path: this.idCardFrontPhoto,
          negative_path: this.idCardBackPhoto,
          gender: Boolean(genderId * 1),
          validity_start_time: startingDate,
          validity_end_time: endDate,
          hand_id_card_path: this.picturesString,
          email: Email,
          qq_num: QQNum,
          wx_num: WxNum
        }
        const res = await this.$api.authentication.reqUserAuth(params)
        if (res.code === 200) {
          Toast(res.data)
          await this.$router.push('/mine')
          // 重新获取
          await this.$store.dispatch('getUserAllInfo')
        }
      }
    }
  },

  destroyed() {
    this.$store.dispatch('clearUserAuditInfo')
  }
}
</script>

<style lang="css" scoped>
.isCompletedAudit {
  display: none;
}
</style>
